package com.ke.service.impl;

import com.ke.dao.ArticleOrderRepository;
import com.ke.dao.ArticleRepository;
import com.ke.pojo.Article;
import com.ke.pojo.ArticleCart;
import com.ke.pojo.ArticleOrder;
import com.ke.pojo.BaseResp;
import com.ke.service.ArticleCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleCartServiceImpl implements ArticleCartService {




    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ArticleRepository articleRepository;

    @Autowired
    ArticleOrderRepository articleOrderRepository;


    /**
     * 添加文章到购物车
     * @param id
     * @param request
     * @return
     */
    @Override
    public BaseResp addArticleCart(Integer id, HttpServletRequest request) {

        //获取用户id
        Integer uid= new Integer(request.getAttribute("id").toString());

        Optional<Article> byId = articleRepository.findById(id);
        Article article = byId.get();
        ArticleCart articleCart = new ArticleCart();
        articleCart.setId(id);
        articleCart.setUserId(uid);
        articleCart.setArticleId(id);
        articleCart.setPrice(article.getPrice());
        articleCart.setArticleName(article.getArticleName());
        articleCart.setArticlePic(article.getPic());
        //存到redis购物车中
        redisTemplate.opsForHash().put("articleCart" + uid.toString(),article.getId().toString(),articleCart);
        return new BaseResp(0,"添加成功!!");
    }

    /**
     * 查询全部文章的购物车
     * @param request
     * @return
     */
    @Override
    public BaseResp findAllArticleCart(HttpServletRequest request) {

        //获取用户id
        Integer uid= new Integer(request.getAttribute("id").toString());
        Boolean flag = redisTemplate.hasKey("articleCart"+uid.toString());
        if(flag){
            //如果redis中存在articleCart,则从redis中查询
            List list = redisTemplate.opsForHash().values("articleCart" + uid.toString());
            return new BaseResp(0,"查询成功!",list);
        }else{
            return new BaseResp(1,"购物车为空!请先添加付费文章!");
        }
    }

    /**
     * 从购物车删除文章
     * @param id
     * @param request
     * @return
     */
    @Override
    public BaseResp deleteArticleCart(Integer id, HttpServletRequest request) {
        //获取用户id
        Integer uid= new Integer(request.getAttribute("id").toString());
        Boolean flag = redisTemplate.hasKey("articleCart" + uid.toString());
        if(flag){
            redisTemplate.opsForHash().delete("articleCart" + uid.toString(),id.toString());
            return new BaseResp(0,"删除成功");
        }else{
            return new BaseResp(1,"购物车为空!请先添加付费文章!");
        }
    }
}
